// Copyright 2013 The golab Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// Package minjs might one day do a better job of minifying JavaScript, but for
// now it is here simply to remove comments from JSON input (comments are not
// allowed in JSON).
package minjs

// RmComments removes line comments and block comments from an []byte.
//
// 	// this is a line comment
// 	/* this is a c-style block comment */
//
// It should be an error if the []byte ends before closing a block comment but
// we ignore it because it seems like a trivial thing to find considering we
// are not doing any other syntax checking.
func RmComments(b []byte) []byte {
	l := len(b)
	i := int(0)
	j := int(0)
	var r []byte
	for {
		if i >= l-1 {
			return append(r, b[j:l]...)
		}
		if b[i] == '/' {
			if b[i+1] == '/' {
				// in line comment
				r = append(r, b[j:i]...)
				i += 2
				// look for end of line
				for {
					if i >= l {
						return r
					}
					if b[i] == '\n' {
						//found end
						j = i
						break
					}
					i++
				}
			} else if b[i+1] == '*' {
				// in block comment
				r = append(r, b[j:i]...)
				i += 2
				// look for end of block
				for {
					if i >= l-1 {
						// actually an error for
						// a non-closing comment
						return r
					}
					if b[i] == '*' {
						if b[i+1] == '/' {
							//found end
							i += 2
							j = i
							break
						}
					}
					i++
				}
			}
		}
		i++
	}
	return r
}
